package com.example.admin.controller.sys;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.admin.SysPermission;
import com.example.admin.SysUser;
import com.example.admin.service.ISysPermissionService;
import com.example.shrio.CurrentUser;
import com.example.util.APIState;
import com.example.util.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 资源权限信息表 前端控制器
 * </p>
 *
 * @author wangkai
 * @since 2019-06-04
 */
@RestController
@Api(value = "系统菜单Controller", tags = {"系统菜单操作接口"})
@RequestMapping("/sys/sysPermission")
public class SysPermissionController {

    @Autowired
    private ISysPermissionService service;

    /**
     * 获取权限
     *
     * @return
     */
    @ApiOperation(value = "系统菜单列表", httpMethod = "POST")
    @PostMapping(value = "/page")
    public AjaxResult page() {
        QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<SysPermission>();
        queryWrapper.orderByAsc("order_num");
        return new AjaxResult(APIState.S00, service.list(queryWrapper));
    }

    /**
     * 保存
     *
     * @param permission
     * @return
     */
    @ApiOperation(value = "系统菜单新增", httpMethod = "POST")
    @PostMapping
    public AjaxResult save(@RequestBody SysPermission permission) {
        if (permission != null) {
            permission.setCreateDate(new Date());
            permission.setCreateUserId(CurrentUser.getAdminUser().getId());
            if (service.insertPermission(permission)) {
                return new AjaxResult(APIState.S00, "保存成功");
            }
        }
        return new AjaxResult(APIState.S01, "保存失败");
    }

    /**
     * 修改
     *
     * @param permission
     * @return
     */
    @ApiOperation(value = "系统菜单编辑", httpMethod = "PUT")
    @PutMapping
    public AjaxResult update(@RequestBody SysPermission permission) {
        if (permission != null && permission.getId() != null) {
            if (permission.insertOrUpdate()) {
                return new AjaxResult(APIState.S00, "保存成功");
            }
        }
        return new AjaxResult(APIState.S01, "保存失败");
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "系统菜单删除", httpMethod = "DELETE")
    @DeleteMapping(value = "/{id}")
    public AjaxResult delete(@PathVariable Long id) {
        if (id != null) {
            SysPermission permission = service.getById(id);
            if (permission != null) {
                if (service.deleteParmission(permission)) {
                    return new AjaxResult(APIState.S00, "保存成功");
                }
            } else {
                return new AjaxResult(APIState.S01, "当前权限不存在请重新刷新列表");
            }
        }
        return new AjaxResult(APIState.S01, "保存失败");
    }

    /**
     * 返回权限list
     *
     * @return
     */
    @ApiOperation(value = "系统菜单list", httpMethod = "GET")
    @GetMapping(value = "/list/permission")
    public AjaxResult geList() {
        if (CurrentUser.getAdminUser().getAccount().equals("admin")) {
            QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<SysPermission>();
            queryWrapper.orderByAsc("order_num");
            return new AjaxResult(APIState.S00, service.list(queryWrapper));
        }
        List<SysPermission> result = new ArrayList<>();
        CurrentUser.getAdminUser().getRoleList().forEach(info -> result.addAll(info.getPermissions()));
        return new AjaxResult(APIState.S00, result);
    }

    @ApiOperation(value = "系统菜单tree", httpMethod = "GET")
    @GetMapping(value = "/list")
    public AjaxResult getList() {
        QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<SysPermission>();
        queryWrapper.orderByAsc("order_num");
        List<SysPermission> list = service.list(queryWrapper);
        if (list != null && list.size() > 0) {
            return new AjaxResult(APIState.S00, list.stream().filter(x -> x.getType().intValue() == 1).map(info -> {
                JSONObject pjson = new JSONObject();
                pjson.put("id", info.getId());
                pjson.put("label", info.getName());
                pjson.put("children", list.stream().filter(x -> x.getType() == 2 && x.getParentId() == info.getId()).map(in -> {
                    JSONObject json = new JSONObject();
                    json.put("id", in.getId());
                    json.put("label", in.getName());
                    return json;
                }).collect(Collectors.toList()));
                return pjson;
            }).collect(Collectors.toList()));
        }
        return new AjaxResult(APIState.S00, new ArrayList<>());
    }

    /**
     * 当前用户权限菜单
     *
     * @return
     */
    @ApiOperation(value = "当前用户权限菜单", httpMethod = "GET")
    @GetMapping(value = "/list/getUserList")
    public AjaxResult getUserList() {
        SysUser sysUser = CurrentUser.getAdminUser();
        List<SysPermission> list = service.getUserList(sysUser);
        List<SysPermission> result = list.stream().filter(info -> info.getFlag().intValue() == 0).collect(Collectors.toList());
        result.sort((x, y) -> x.getOrderNum().compareTo(y.getOrderNum()));
        return new AjaxResult(APIState.S00, result);
    }

    @ApiOperation(value = "角色权限菜单", httpMethod = "GET")
    @GetMapping(value = "/list/{roleId}")
    public AjaxResult getRoleList(@PathVariable Integer roleId) {
        List<SysPermission> list = service.getRoleList(roleId);
        list.sort((x, y) -> x.getOrderNum().compareTo(y.getOrderNum()));
        return new AjaxResult(APIState.S00, list);
    }


}
